/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;


public final class DbUtils {
	private DbUtils() {}  // never

	public static <K extends DbKey,V extends DbObject<K,V>> V getGoodCopy(V obj) {
		if( obj==null )
			return null;
		DbRecord<K,V> record = obj.getDbRecord();
		return !record.isStale() ? obj
			: record.getDbTable().findByPrimaryKey(record.getPrimaryKey());
	}

	public static <K extends DbKey,V extends DbObject<K,V>> void uncache(V obj) {
		DbRecord<K,V> record = obj.getDbRecord();
		record.getDbTable().uncache(record.getPrimaryKey());
	}

	public static boolean isStale(DbObject obj) {
		return obj==null || obj.getDbRecord().isStale();
	}

	public static boolean isStale(DbObject[] objs) {
		if( objs==null )
			return true;
		for( int i=0; i<objs.length; i++ ) {
			if( isStale(objs[i]) )
				return true;
		}
		return false;
	}

	public static boolean isEqual(DbObject o1,DbObject o2) {
		DbRecord r1 = o1.getDbRecord();
		DbRecord r2 = o2.getDbRecord();
		if( !r1.isInDb() )
			return o1.equals(o2);
		return r1.getPrimaryKey().equals(r2.getPrimaryKey());
	}

	public static Date getDate(ResultSet rs,String columnName) throws SQLException {
		java.sql.Timestamp ts = rs.getTimestamp(columnName);
		return ts==null ? null : new Date(ts.getTime());
	}

	public static void test(DbDatabase db) {
		try {
			Connection con = db.getConnection();
			try {
				Statement stmt = con.createStatement();
				stmt.executeQuery("select 1");
				stmt.close();
			} finally {
				con.close();
			}
		} catch(SQLException e) {
			throw new RuntimeException("test failed",e);
		}
	}
}
